<template>
  <div class="charts_container" ref="echartsPoly"></div>
</template>

<script>
export default {
  name: 'UIRchart',
  data () {
    return {
      chartInstance: null,
      reald: null,
      initOption: null,
      timer: null,
      ployData: [],
      colorg: ['rgb(0,108,237)', 'rgb(0,207,255)', 'rgb(0,255,255)', 'rgb(6,253,188)']
    }
  },
  created () {
  },
  mounted () {
    this.initChart()
  },
  props: {
    realData: {
      type: Array,
      required: true
    }
  },
  watch: {
    realData: {
      handler (newVal, oldVal) {
        // console.log('newVal终于出来了电压电阻', newVal, oldVal)
        if (newVal.length > 0) {
          this.reald = JSON.parse(JSON.stringify(newVal))
          this.timeWay(this.reald)
          var copys = JSON.parse(JSON.stringify(this.reald))
          copys[0].splice(0, 1)
          const seriesGroup = []
          var markPoint = {
            symbol: 'path://m 0,0 h 48 v 20 h -30 l -6,10 l -6,-10 h -6 z',
            symbolSize: [33, 24],
            symbolKeepAspect: true,
            itemStyle: {
              color: 'rgb(0,213,250,0.4)'
            },
            label: {
              fontSize: 10,
              offset: [0, -2]
            },
            symbolOffset: ['23%', '-60%'],
            data: [
              { type: 'max', name: 'Max' },
              { type: 'min', name: 'Min' }
            ]
          }
          copys[0].forEach((item, index) => {
            seriesGroup.push({
              encode: {
                // 将 "amount" 列映射到 X 轴。
                x: 'createTime',
                // 将 "product" 列映射到 Y 轴。
                y: [item]
              },
              name: item,
              type: 'line',
              visualMap: false,
              // symbol: 'circle', // 节点样式
              symbol: copys[0][0].slice(-2) === '炉阻' ? 'none' : 'circle', // 节点样式
              lineStyle: {
                width: 2,
                color: this.colorg[index]
              },
              // areaStyle: copys[0][0].slice(-2) === '炉阻' ? { opacity: 0.2 } : null,
              markPoint: copys[0][0].slice(-2) === '炉阻' ? markPoint : {},
              itemStyle: {
                color: this.colorg[index]
                // opacity: 0.5
                // borderColor: 'rgb(0,115,100)',
                // borderWidth: 0,
                // shadowColor: 'rgba(0, 0, 0, 0)',
                // shadowBlur: 0,
                // shadowOffsetY: 0,
                // shadowOffsetX: 0
              }
            })
          })
          this.timer = setTimeout(() => {
            this.updateChart(seriesGroup, this.reald, copys[0][0].slice(-2), newVal)
          }, 800)
        }
      },
      immediate: true
    }
  },
  beforeDestroy () {
    window.removeEventListener('resize', () => {
      this.chartInstance.resize()
    })
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    timeWay (arrBig) {
      for (var i = 1; i < arrBig.length; i++) {
        arrBig[i][0] = arrBig[i][0].substring(5, arrBig[i][0].length - 3)
      }
    },
    turntoTime (dates) { // 转毫秒
      dates = dates.replace(new RegExp('-', 'gm'), '/')
      return (new Date(dates)).getTime()
    },
    initChart () {
      this.initOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(0, 255, 233,0)'
                  },
                  {
                    offset: 0.5,
                    color: 'rgba(255, 255, 255,1)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(0, 255, 233,0)'
                  }
                ],
                global: false
              }
            }
          }
        },
        grid: {
          top: '24%',
          left: '6%',
          right: '5%',
          bottom: '0%',
          containLabel: true
        },
        toolbox: {
          show: true,
          feature: {
            // dataZoom: {
            //   yAxisIndex: 'none' // 缩放功能
            // },
            // dataView: { readOnly: false }, // 数据表格功能
            // magicType: { type: ['line', 'bar'] }
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisTick: { // 不显示轴刻度
            show: false
          },
          splitLine: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: '#a6bde9'
            }
          },
          axisLabel: {
            interval: 'auto',
            formatter: function (value) {
              let ret = '' // 拼接加\n返回的类目项
              var maxLength = 6 // 每行最多个数
              var valLength = value.length // x轴一个项的总数
              var rowN = Math.ceil(valLength / maxLength)
              if (rowN > 1) { // 如果大于5个字符
                for (let i = 0; i < rowN; i++) {
                  let temp = ''
                  temp = value.substring(i * maxLength, i * maxLength + maxLength) + '\n'
                  ret += temp
                }
                return ret
              } else {
                return value
              }
            },
            textStyle: {
              fontSize: 8
            }
          }
        },
        yAxis: [
          {
            // name: '风机频率(hz)',
            nameTextStyle: {
              color: 'rgb(154, 170, 203)',
              padding: [0, 0, 0, -22]
            },
            type: 'value',
            axisLabel: {
              interval: 'auto',
              formatter: '{value}',
              color: 'rgb(154, 170, 203)'
            },
            axisTick: { // 不显示轴刻度
              show: false
            },
            // nameLocation: 'start',
            // min: 'dataMin',
            // max: 'dataMax', // y轴范围
            splitLine: { // 属于y轴的是grid横线
              show: false,
              lineStyle: {
                type: 'dashed'
              }
            }
          }
        ],
        dataset: {
          source: []
        },
        series: []
      }
      this.chartInstance = this.$echarts.init(this.$refs.echartsPoly)
      this.chartInstance.setOption(this.initOption, true)
      this.echartsResize()
    },
    echartsResize () {
      window.addEventListener('resize', () => {
        this.chartInstance.resize()
      })
    },
    updateChart (seriesGroup, realData, name, newVal) {
      var copysData = JSON.parse(JSON.stringify(newVal))
      const grid1 = {
        top: '28%',
        left: '6%',
        right: '5%',
        bottom: '2%',
        containLabel: true
      }
      const grid2 = {
        top: '11%',
        left: '5%',
        right: '5%',
        bottom: '13%',
        containLabel: true
      }
      var gridFinal = name === '炉阻' ? grid2 : grid1
      const legend1 = {
        top: '1%',
        itemWidth: 15,
        itemHeight: 8,
        textStyle: {
          color: '#a6bde9',
          fontSize: 10
        }
      }
      const legend2 = {
        top: '0%',
        itemWidth: 15,
        itemHeight: 8,
        textStyle: {
          color: '#a6bde9',
          fontSize: 10
        }
      }
      var legends = name === '炉阻' ? legend2 : legend1
      var minsTemper = function (value) {
        return Math.ceil(value.min) // 想上取整
      }
      var maxsTemper = function (value) {
        return Math.ceil(value.max)
      }
      // var minR = function (value) {
      //   // return value.min.toFixed(1)
      //   value.min = value.min * 10
      //   var fina = Math.floor(value.min) / 10
      //   return fina
      // }
      var maxR = function (value) {
        // return value.max.toFixed(1)
        value.max = value.max * 10
        var finas = Math.ceil(value.max) / 10
        return finas
      }
      var visualMaps = ''
      var markAreas = ''
      if (name === '炉阻') {
        const realDataCopy = JSON.parse(JSON.stringify(realData))
        realDataCopy.splice(0, 1)
        var spliceArr = []
        realDataCopy.forEach((item, index) => {
          // item[0] = this.turntoTime(copysData[index + 1][0])
          spliceArr.push(item[1])
        })
        // console.log('spliceArr', spliceArr)
        var pieceSelect = []
        var markAreasTime = []
        for (let i = 0; i < spliceArr.length; i++) {
          if (spliceArr[i] >= spliceArr[i + 1] && spliceArr[i + 1] < spliceArr[i + 2]) {
            pieceSelect.push({
              // gte: spliceArr[i],
              gte: i,
              // lte: spliceArr[i + 2],
              lte: i + 2,
              color: 'rgba(255,0,0,0.6)'
            })
            markAreasTime.push([
              {
                name: 'warn',
                xAxis: this.turntoTime(copysData[i][0])
              },
              {
                xAxis: this.turntoTime(copysData[i + 2][0])
              }
            ])
          }
        }
        if (pieceSelect.length === 0) {
          visualMaps = ''
          markAreas = ''
        } else {
          visualMaps = { // 数据映射 也可以维度映射
            type: 'piecewise',
            show: false,
            dimension: 0, // 如果上面gte用 下标的话 就用时间的那个轴的映射 如果用数据的话 就用第二列数据的映射
            pieces: pieceSelect,
            // precision: 4, // 设置小数精度，默认0没有小数
            outOfRange: {
              color: 'rgba(0,108,237,0.8)'
            }
          }
          markAreas = {
            silent: false,
            itemStyle: {
              color: 'rgba(255, 173, 177, 0.4)'
            },
            data: markAreasTime
          }
        }
      }
      const dataOption = {
        series: seriesGroup,
        yAxis: [{
          name: name === '炉阻' ? '' : name,
          min: name === '炉阻' ? 0 : minsTemper,
          max: name === '炉阻' ? maxR : maxsTemper
        }],
        grid: gridFinal,
        legend: legends,
        // visualMap: name === '炉阻' ? visualMaps : '', // 写成 '' 而不是 {}
        // markArea: name === '炉阻' ? markAreas : '',
        xAxis: {
          axisLabel: {
            interval: name === '炉阻' ? 12 : 10
          }
        },
        dataset: {
          source: realData // 数组
        }
      }
      // console.log('dataOption', dataOption)
      this.chartInstance.setOption(dataOption)
    }
  }
}
</script>

<style  scoped>
.charts_container {
  width: 100%;
  height: 100%;
}
</style>
